<?php

namespace App\Admin\Controllers;

use App\Models\AdminUsersModel;
use App\Models\AdminUsersRelatedModel;
use App\Models\FinanceExpensesModel;
use App\Models\FinanceIncomeModel;
use App\Models\StuffWagesModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Auth;

class ReportFormsController extends AdminController
{
    public function title(): string
    {
        return '员工报表';
    }

    public function stuff(Content $content)
    {
        return Admin::content(function (Content $content) {
            $content->header($this->title());
            $content->description('报表');
            $content->body(view('reportForms.stuff', [
                'data' => self::allStuff()
            ]));
        });
    }

    public function allStuff()
    {
        $users = AdminUsersModel::query()
            ->leftJoin('admin_users_related', 'admin_users.id', '=', 'admin_users_related.user_id')
            ->select('user_id', 'name');
        if (ISADMIN) $users->where('admin_users_related.main_id', '>', 0);
        else {
            if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) {
                $users->orWhere('admin_users_related.main_id', MAINID)
                    ->orWhere('user_id', MAINID);
            } else $users->where('admin_users_related.user_id', USERID);
        }
        return $users->get()->toArray();
    }

    public function total(Content $content)
    {
        $incomeNotAudit = FinanceIncomeModel::query()
            ->where('status', 0);
        if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) $incomeNotAudit->where('finance_income.main_id', MAINID);

        $data['not_audit'] = $incomeNotAudit->sum('actual_income_amount');

        $incomeSuccess = FinanceIncomeModel::query()
            ->where('status', 1);
        if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) $incomeSuccess->where('finance_income.main_id', MAINID);
        $data['success'] = $incomeSuccess->sum('actual_income_amount');

        $incomeRefuse = FinanceIncomeModel::query()
            ->where('status', 2);
        if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) $incomeRefuse->where('finance_income.main_id', MAINID);
        $data['refuse'] = $incomeRefuse->sum('actual_income_amount');

        $wagesNotAudit = StuffWagesModel::query()
            ->where('status', 0);
        if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) $wagesNotAudit->where('stuff_wages.main_id', MAINID);
        $data['not_audit1'] = $wagesNotAudit->sum('actual_wages');

        $wagesSuccess = StuffWagesModel::query()
            ->where('status', 1);
        if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) $wagesSuccess->where('stuff_wages.main_id', MAINID);
        $data['success1'] = $wagesSuccess->sum('actual_wages');

        $wagesRefuse = StuffWagesModel::query()
            ->where('status', 2);
        if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) $wagesRefuse->where('stuff_wages.main_id', MAINID);
        $data['refuse1'] = $wagesRefuse->sum('actual_wages');

        $expenseNotAudit = FinanceExpensesModel::query()
            ->where('status', 0);
        if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) $expenseNotAudit->where('finance_expenses.main_id', MAINID);
        $data['not_audit2'] = $expenseNotAudit->sum('amount');

        $expenseSuccess = FinanceExpensesModel::query()
            ->where('status', 1);
        if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) $expenseSuccess->where('finance_expenses.main_id', MAINID);
        $data['success2'] = $expenseSuccess->sum('amount');

        $expenseRefuse = FinanceExpensesModel::query()
            ->where('status', 2);
        if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) $expenseRefuse->where('finance_expenses.main_id', MAINID);
        $data['refuse2'] = $expenseRefuse->sum('amount');

        $data['balance'] = bcsub($data['success'], bcadd($data['success1'], $data['success2'], 2), 2);
        return Admin::content(function (Content $content) use ($data) {
            $content->header('总报表');
            $content->description('报表');
            $content->body(view('reportForms.total', [
                'data' => array_merge($data, self::chart())
            ]));
        });
    }

    public function chart()
    {
        // 获取当前年份
        $year = date('Y');
        $incomeData = FinanceIncomeModel::query()
            ->selectRaw('SUM(actual_income_amount) as total_income, MONTH(income_date) as month')
            ->where('status', 1);
        if (!ISADMIN) $incomeData->where('main_id', MAINID);
        $incomeData = $incomeData->whereYear('income_date', $year)
            ->groupBy('month')
            ->pluck('total_income', 'month')
            ->toArray();

        $expenseData = FinanceExpensesModel::query()
            ->selectRaw('SUM(amount) as total_expenses, MONTH(date) as month')
            ->where('status', 1);
        if (!ISADMIN) $expenseData->where('main_id', MAINID);
        $expenseData = $expenseData->whereYear('date', $year)
            ->groupBy('month')
            ->pluck('total_expenses', 'month')
            ->toArray();

        $wagesData = StuffWagesModel::query()
            ->selectRaw('SUM(actual_wages) as total_wages, MONTH(date) as month')
            ->where('status', 1);
        if (!ISADMIN) $wagesData->where('main_id', MAINID);
        $wagesData = $wagesData->whereYear('date', $year)
            ->groupBy('month')
            ->pluck('total_wages', 'month')
            ->toArray();

        $months = range(1, 12);
        $income = [];
        $expense = [];
        $wages = [];

        foreach ($months as $month) {
            $income[] = $incomeData[$month] ?? 0;
            $expense[] = $expenseData[$month] ?? 0;
            $wages[] = $wagesData[$month] ?? 0;
        }

        return [
            'income' => $income,
            'expense' => $expense,
            'months' => $months,
            'wages' => $wages,
        ];
    }
}
